﻿using System;
using System.Windows;
using System.Windows.Input;
using Moonwish.Core;
using Moonwish.Core.Command;
using Moonwish.Foundation.Interface;
using Moonwish.Foundation.ValueObjects;
using Moonwish.Foundation.Views.ValueObjects;

namespace Moonwish.Foundation.ViewModels.ValueObjects
{
    /// <summary>
    /// 值对象分类ViewModel,write by zhlin 2010-03-13.
    /// </summary>
    public class ValueObjectClassViewModel : ViewModelBase, IFoundationCommands
    {
        public event EventHandler SelectedItemChanged;
        private ValueObjectClassCollection _valueObjectClasses = new ValueObjectClassCollection();

        public ValueObjectClassViewModel()
        {
            if (!IsInDesignMode)
            {
                PublishCommand = new RelayCommand<ValueObjectClass>(Publish);
                DisableCommand = new RelayCommand<ValueObjectClass>(Disable);
            }
        }

        public ValueObjectClassCollection Data
        {
            get { return _valueObjectClasses; }
            set
            {
                _valueObjectClasses = value;
                RaisePropertyChanged("Data");
            }
        }

        private ValueObjectClass _selectedItem;
        /// <summary>
        /// 当前选中数据行。
        /// </summary>
        public ValueObjectClass SelectedItem { 
            get { return _selectedItem; }
            set
            {
                if (value != _selectedItem)
                {
                    _selectedItem = value;

                    RaisePropertyChanged("SelectedItem");

                    UpdateButtonStatus();

                    var handler = SelectedItemChanged;

                    if (handler != null)
                    {
                        handler(this, new EventArgs());
                    }
                }
            }
        }

        protected override void Add()
        {
            var newItem = new ValueObjectClass();
            newItem.ApplyButtonVisibility = Visibility.Visible;
            var dialog = new ValueObjectClassDialog(newItem);
            dialog.Title = "新增";
            dialog.Show();
            dialog.ApplyOk += (s, e) =>
            {
                Data.AddCompleted += (s1, e1) =>
                {
                    SelectedItem = newItem;
                    IsBusy = false;
                    newItem = new ValueObjectClass();
                    newItem.ApplyButtonVisibility = Visibility.Visible;
                    dialog.DataContext = newItem;
                    UpdateButtonStatus();
                };
                Data.Add(newItem);
                IsBusy = true;
                
            };
            dialog.Closed += (s, e) =>
            {
                if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
                {
                    Data.AddCompleted += (s1, e1) =>
                    {
                        IsBusy = false;
                        SelectedItem = newItem;
                        UpdateButtonStatus();
                    };
                    Data.Add(newItem);
                    IsBusy = true;
                }
            };
        }

        protected override void Edit(object selectedItem)
        {
            var originalItem = (ValueObjectClass)selectedItem;
            var editItem = originalItem.Clone();
            editItem.ApplyButtonVisibility = Visibility.Collapsed;
            Edit(editItem, dialog =>
            {
                if (dialog.HasValue && dialog.Value)
                {
                    originalItem.Override(editItem);
                    originalItem.SaveChangedCompleted += (s, e) =>
                    {
                        IsBusy = false;
                    };
                    originalItem.SaveChangedAsync();
                    IsBusy = true;
                }
            });
        }

        protected override void Edit(object selectedItem, Action<bool?> finishedCallback)
        {
            var editItem = (ValueObjectClass) selectedItem;
            var dialog = new ValueObjectClassDialog(editItem);
            dialog.Title = "编辑";
            dialog.Show();
            dialog.Closed += (s, e) =>
            {
                if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
                {
                    finishedCallback(dialog.DialogResult);
                }
            };
        }

        /// <summary>
        /// 删除数据。
        /// </summary>
        /// <param name="selectedItem"></param>
        protected override void Delete(object selectedItem)
        {
            var dataItem = (ValueObjectClass)selectedItem;
             if (MessageBox.Show(
                 string.Format("确定要删除“{0}”吗？", dataItem.Name), "删除提示", MessageBoxButton.OKCancel) 
                 != MessageBoxResult.OK)
             {
                 return;
             }
            Data.RemoveCompleted += (s, e) =>
            {
                IsBusy = false;
                UpdateButtonStatus();
            };
            Data.Remove(dataItem);
            IsBusy = true;
        }

        public ICommand PublishCommand
        {
            get; set;
        }

        /// <summary>
        /// 发布数据。
        /// </summary>
        /// <param name="selectedItem"></param>
        public void Publish(object selectedItem)
        {
            var dataItem = (ValueObjectClass)selectedItem;
            if (MessageBox.Show(
                 string.Format("确定要发布“{0}”吗？", dataItem.Name), "发布提示", MessageBoxButton.OKCancel)
                 != MessageBoxResult.OK)
            {
                return;
            }
            dataItem.PublishCompleted += (s, e) =>
            {
                IsBusy = false;
                if (e.Error != null)
                {
                    MessageBox.Show((e.Error.InnerException ?? e.Error).Message);
                    return;
                }
                
                UpdateButtonStatus();
            };
            dataItem.PublishAsync();
            IsBusy = true;
        }

        public ICommand DisableCommand { get; set; }

        /// <summary>
        /// 作废数据。
        /// </summary>
        /// <param name="selectedItem"></param>
        public void Disable(object selectedItem)
        {
            var dataItem = (ValueObjectClass)selectedItem;
            if (MessageBox.Show(
                 string.Format("确定要作废“{0}”吗？", dataItem.Name), "作废提示", MessageBoxButton.OKCancel)
                 != MessageBoxResult.OK)
            {
                return;
            }
            dataItem.DisableCompleted += (s, e) =>
            {
                IsBusy = false;
                UpdateButtonStatus();
            };
            dataItem.DisableAsync();
            IsBusy = true;
        }

        public void UpdateButtonStatus()
        {
            RaisePropertyChanged(() => CanEdit);
            RaisePropertyChanged(() => CanPublish);
            RaisePropertyChanged(() => CanDisable);
            RaisePropertyChanged(() => CanDelete);
        }

        public bool CanEdit
        {
            get { return SelectedItem != null; }
        }

        public bool CanPublish
        {
            get
            {
                return SelectedItem != null && SelectedItem.DataStatus == DataStatus.New;
            }
        }

        public bool CanDisable
        {
            get
            {
                return SelectedItem != null && SelectedItem.DataStatus == DataStatus.Released;
            }
        }

        public bool CanDelete
        {
            get { return SelectedItem != null && SelectedItem.DataStatus == DataStatus.New; }
        }
    }
}